package com.itzhoun.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author :  xwtec
 * @date : 2024/2/4 10:52
 */
public class DecryUtils {

    static String priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJWKfgNg7/63iRrkcvC4YIzf+PbyUzyIsNBouk41vow5GesjjlCCpUPmPz14Z8FhO96xhtwhMOhg5jYtEWGq+sNHxeSsIdadBLs4Z7yjNKjwFGs1AFpqyF3bOw+yDp50SO3wZ9dV6+7sWo6rbBrfdRnUKmc2Q1evz6DaIxRkeMxJAgMBAAECgYATk0yJnq/r9RSii5MsRcaFym/py7DvtKkIrxzsTgbCjlsBN+dSTLfbmpFet5tFajgPH8gamtGvKbgZEW88DMjEgdvH+BlFUSzQHBw+KvY6vAj5fi8bl6xYlic/gYnbFHeEZjHTACIuL2inrLeXkVtEIu2XP6qoiNtq5jjMLr97vQJBANsfloGEw3N7kfhYw5JYYlJEdo+hC+sWTWzdrWKWIQ3nv6D/8PXMmp2T9vZY365xus0Jdp0p+YOAjM02JTlQv38CQQCutRx8ZhEXB+oM/b8raA6RhtxpMkEjCxHwJSzQKT7QrsyuaSW6S102XwOwNARn++V7g5Ysmj39Zr+7h7vTtFg3AkAvKdthQUw4XQ6MH77ojvGKt4W1YHqKPSCpIAWjxKCUt579bllU7pcQ97oeR/7NM1l7rF/FcDVuYorr2I2mioTNAkBCEvktCyUXgsTAGQ++COLJoymlF36PFFa6bjTenVrGbfW3WMkOBgbA03p/n4yzDw+hgQjA4azkM4H8GL+ut5xNAkEAuaS5R0CVebNwJ9Yjx2jpAG+kiwkHFa0b5mrPprpAWHhti5LJkaTCZ7F5j4ohCotDKveVt4Kg3jzzSjTeV1CtXg==";
    static String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVin4DYO/+t4ka5HLwuGCM3/j28lM8iLDQaLpONb6MORnrI45QgqVD5j89eGfBYTvesYbcITDoYOY2LRFhqvrDR8XkrCHWnQS7OGe8ozSo8BRrNQBaashd2zsPsg6edEjt8GfXVevu7FqOq2wa33UZ1CpnNkNXr8+g2iMUZHjMSQIDAQAB";

    /**
     * 公钥加密
     */
    public static String pubKeyEncryption(String dateStr) {
        RSA rsa = SecureUtil.rsa(null, pubKey);
        return rsa.encryptBase64(dateStr, StandardCharsets.UTF_8, KeyType.PublicKey);
    }

    /**
     * 私钥解密
     */
    public static String priKeyDecryption(String dateStr) {
        RSA rsa = SecureUtil.rsa(priKey, null);
        return rsa.decryptStr(dateStr, KeyType.PrivateKey);
    }

    static String key = "ynckcotest$@2034";

    /**
     * 加密
     *
     * @param dateStr
     * @return
     */
    public static String aesEncryption(String dateStr) {
        if (!StringUtils.hasText(dateStr)) {
            return null;
        }
        AES aes = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8));
        return aes.encryptHex(dateStr, StandardCharsets.UTF_8);
    }

    /**
     * 解密
     */
    public static String aesDecryption(String dateStr) {
        if (!StringUtils.hasText(dateStr)) {
            return null;
        }
        try {
            AES aes = SecureUtil.aes(key.getBytes(StandardCharsets.UTF_8));
            return aes.decryptStr(dateStr, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败");
        }
    }
}
